﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using System.Web;
using System.IO;

namespace Core.DS
{
    public static partial class statistics
    {
        public static dynamic uploadReport(int eid, string username, HttpPostedFileBase userfile, string ext)
        {
            var sql = new Sql.SqlDataContext();
            var u = sql.User.First(row => row.username == username);
            if (u.sid == null) return new
            {
                success = false,
                msg = "仅学生用户能上传实验报告！"
            };
            var e = sql.DSExperiment.FirstOrDefault(row => row.eid == eid);
            if (e == null) return new
            {
                success = false,
                msg = "实验不存在"
            };
            if (e.startTime != null)
                if (e.startTime.Value > DateTime.Now) return new
                {
                    success = false,
                    msg = "实验未开始，请在实验开始时间之后提交。"
                };

            var path = string.Format("{0}Report\\e{1}\\", ConfigurationManager.AppSettings["SafePath"], eid);
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            path = string.Format("{0}{1}_{2}{3}", path, u.sid, u.name, ext);
            userfile.SaveAs(path);
            var ue = sql.DSExperimentSolve.FirstOrDefault(row => row.eid == eid && row.username == username);
            if (ue == null)
            {
                ue = new Sql.DSExperimentSolve
                  {
                      eid = eid,
                      username = username,
                      sid = u.sid,
                      report = true,
                      reportTime = DateTime.Now,
                      reportContent = ""
                  };
                sql.DSExperimentSolve.InsertOnSubmit(ue);
            }
            else
            {
                ue.report = true;
                ue.reportTime = DateTime.Now;
            }
            sql.SubmitChanges();
            functional.word2txt(eid, u, userfile, ext, path);
            return new
            {
                success = true
            };
        }
    }
}
